//
//  OMServiceModalSubmitViewController.m
//  OMENGO
//
//  Created by 梁尚嘉 on 2016/12/23.
//  Copyright © 2016年 Kamfat. All rights reserved.
//

#import "OMServiceModalSubmitViewController.h"
#import "XZLCustomSelectionView.h"
@interface OMServiceModalSubmitViewController ()

@end

@implementation OMServiceModalSubmitViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.sectionHeaderHeight = DBL_EPSILON;
    [self setPrize:@"0"];
    [self configure];

    if (self.productKey) {
        [self startAnimating:YES];
        [self getProduct];
    }
    // Do any additional setup after loading the view.

    @weakify(self);
    [SMNotificationMonitorRACSignal(OMDELIVERY_ADDRESS_DELETE_NOTIFICATION) subscribeNext:^(id x) {
        @strongify(self);
        [self reloadDataFromNetWork];
    }];
}

- (void)configure
{

}

#pragma mark - network

- (void)reloadDataFromNetWork
{
    [self getProduct];
}

- (void)getProduct
{
    if (!self.productKey) {
        return;
    }
    [KTHttpUtils GET_NOCACHE:@"app/fourPage"
                  parameters:@{@"key":self.productKey}
                    progress:nil
                  completion:^(id responseObject, BOOL isSuccess, NSString *message) {
                      if (isSuccess) {
                          self.product = [OMProduct mj_objectWithKeyValues:responseObject[OMDataKey][@"product"]];
                          self.deliveryInfo = [OMDeliveryInfo mj_objectWithKeyValues:responseObject[OMDataKey][@"receiver"]];
                          self.coupons = [OMCheapModel mj_objectArrayWithKeyValuesArray:responseObject[OMDataKey][@"coupon"]];
                          [self.tableView reloadData];
                          [self startAnimating:NO];
                      }else {
                          [self showNetWorkError];
                      }
                  }];
}

#pragma mark - Getters
- (UIButton *)confirmButton
{
    if (!_confirmButton) {
        _confirmButton = [UIButton new];
        [_confirmButton setTitle:@"确认" forState:UIControlStateNormal];
        [_confirmButton setTitleColor:SM_blackColor forState:UIControlStateNormal];
        [_confirmButton setBackgroundImage:[UIImage imageWithColor:SM_sangouColor] forState:UIControlStateNormal];
        [_confirmButton setBackgroundImage:[UIImage imageWithColor:RGBACOLOR(0, 0, 0, .26)] forState:UIControlStateDisabled];
        _confirmButton.titleLabel.font = SM_CFont(36);
        [_confirmButton addTarget:self action:@selector(submitAction:) forControlEvents:UIControlEventTouchUpInside];

    }
    return _confirmButton;

}

- (UILabel *)prizeLabel
{
    if (!_prizeLabel) {
        _prizeLabel = [UILabel new];
        _prizeLabel.font = SM_CFont(33);
        _prizeLabel.textAlignment = NSTextAlignmentCenter;
        _prizeLabel.text = @"￥0.00";
        _prizeLabel.textColor = HEXCOLOR(@"#FC5E5F");
    }
    return _prizeLabel;
}

- (void)setPrize:(NSString *)price
{
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc]initWithString:@"总价：" attributes:@{NSForegroundColorAttributeName:SM_blackColor}];
    if (price.length) {
        price = [@"￥" stringByAppendingString:price];
        NSAttributedString *priceAttri = [[NSAttributedString alloc]initWithString:price attributes:@{NSForegroundColorAttributeName:HEXCOLOR(@"#FC5E5F")}];
        [attri appendAttributedString:priceAttri];
    }
    self.prizeLabel.attributedText = attri;
}

- (void)selectionViewWithTitle:(NSString *)title
                     dataArray:(NSArray <NSString *>*)dataArray
                      OnSelect:(void (^)(NSInteger index))selection{
    if (!dataArray.count) {
        [OMHUD HUDInfo:@"无此商品"];
        return;
    }
    XZLCustomSelectionView *selectView = [XZLCustomSelectionView new];
    selectView.title = title;
    selectView.dataArray = dataArray;
    [selectView showInView:SMKeyWindow];
    [selectView setOnSelect:selection];
}
#pragma mark - Actions
- (void)submitAction:(UIButton *)button
{

}

- (void)submitWithoutPaymentWithParameters:(NSDictionary *)parameters
{
    [self submitWithPayment:NO withParameters:parameters];
}

- (void)submitWithParameters:(NSDictionary *)parameters
{
    [self submitWithPayment:YES withParameters:parameters];
}

- (void)submitWithPayment:(BOOL)needPay withParameters:(NSDictionary *)parameters
{
    if (!self.deliveryInfo.address.length) {
        [OMHUD HUDInfo:@"请选择服务地址"];
        return;
    }

    [self startAnimating:true];
    [KTHttpUtils POST:_requestUrl?_requestUrl:@"order/create"
           parameters:parameters
             progress:nil
           completion:^(id responseObject, BOOL isSuccess, NSString *message) {

               [self startAnimating:NO];
               if (isSuccess) {
                   SMNotificationPost(OMORDER_NEED_REFRESH_NOTIFICATION, nil);

                   OMOrder *order = [OMOrder mj_objectWithKeyValues:responseObject[OMDatumKey]];
                   order.paymentMethodName = parameters[@"paymentName"];
                   [self handleNavigationWithOrder:order];

                   [OMHUD HUDHide];

               }else {
                   [OMHUD HUDError:message];
               }
           }];
}


- (void)handleNavigationWithOrder:(OMOrder *)order
{
    if (order.status == pendingPayment) {
        NaviPush(@"KTLemonPaymentViewController", (@{@"title":@"支付",@"order":order,@"isRepay":@(NO)}));
    }else {
        NaviPush(@"OMPaySuccessViewController", @{@"order":order});
    }

}

- (void)gotoSelectCoupon
{
    NaviPush(@"OMCouponSelectionViewController", (@{@"title":@"选择优惠券",@"delegate":self}));
}

#pragma mark - tableview delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _cellArray.count;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.cellArray[indexPath.section];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [[self.cellArray[indexPath.section] class] cellHeight];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return SM_SIZE(15);
}


#pragma mark - Setters
- (void)setCoupons:(NSArray<OMCheapModel *> *)coupons
{
    _coupons = coupons;
    if (coupons.count) {
        self.selectedCoupon = coupons[0];
    }else {
        self.selectedCoupon = nil;
    }
}

- (void)setSelectedCoupon:(OMCheapModel *)selectedCoupon
{
    _selectedCoupon = selectedCoupon;
    if (_selectedCoupon) {
        self.couponCell.inputTF.text = selectedCoupon.name;
    }else {
        self.couponCell.inputTF.text = self.coupons.count ? @"未使用优惠券" : @"无可用优惠券";
    }

}

#pragma mark - OMSelectionCtrlProtocol
- (void)ctrl:(id)controller didSelectObject:(OMCheapModel *)object
{
    self.selectedCoupon = object;
}

#pragma mark - OMDeliveryAddressViewCtrlDelegate
- (void)setDeliveryInfo:(OMDeliveryInfo *)deliveryInfo
{
    _deliveryInfo = deliveryInfo;
    [self.addressCell configureCellWithObj:self.deliveryInfo];
}

#pragma mark - OMDeliveryAddressViewCtrlDelegate
- (void)didSelectDeliveryInfo:(OMDeliveryInfo *)deliveryInfo
{
    self.deliveryInfo = deliveryInfo;
}
@end
